import { createSlice, createAsyncThunk, isRejected } from "@reduxjs/toolkit"

// 1. 定义异步 action
// createAsyncThunk 有两个参数：
// 第一个参数是 action 的 type 前缀，
// 第二个参数是一个返回 Promise 的函数，
// 这个函数接受一个参数，这个参数是 dispatch 时传入的值
export const fetchCount = createAsyncThunk(
  "counter/fetchCount",
  async (amount) => {
    // 模拟请求，1秒后返回 amount
    const res = await new Promise(resolve =>
      setTimeout(() => resolve({ data: amount }), 3000)
    )
    return res.data // 最终会作为 action.payload 传入 reducer
  }
)

export const fetchCountAdd = createAsyncThunk(
  "counter/fetchCountAdd",
  async () => {
    await new Promise((resolve) => {
      setTimeout(() => resolve(), 1000)
    })
  }
)

const counterSlice = createSlice({
  name: "counter",
  initialState: { value: 0, loading: false },
  reducers: {
    // 普通同步逻辑
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    }
  },
  // 异步写这里
  // 跟Promise的三种状态对应
  // 异步action可以写多个
  extraReducers: (builder) => {
    // 处理异步 action 的生命周期
    builder
      // 相对type: "counter/fetchCount/pending"
      .addCase(fetchCount.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchCount.fulfilled, (state, action) => {
        console.log('action=>', action);
        state.loading = false
        state.value = action.payload // 把返回的结果加到 value 上
      })
      .addCase(fetchCount.rejected, (state) => {
        state.loading = false
      })
      .addCase(fetchCountAdd.fulfilled, (state) => {
        state.value++
      })
      // // RTK通过addMatcher使用 matcher 来处理多个异步 action 的相同状态
      // // isPending, isFulfilled, isRejected，可以统一处理多个异步 action
      // .addMatcher(isRejected(fetchCount, fetchCountAdd), (state, action) => {
      //   state.loading = false;
      // });
  }
})

export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer
